import time

from flask import Flask, jsonify, render_template
import SerialModule as sm
serr = sm.initConnection('192.168.1.69', 7018)

app = Flask(__name__)

# 固定显示字符配置
BUTTON_ACTIONS = {
    'up': "↑",
    'down': "↓ ",
    'left': "← ",
    'right': "→",
    
}

ACTION_REPEAT = 1
@app.route('/')
def home():
    return render_template('index.html')
@app.route('/button/<direction>', methods=['POST'])
def button_action(direction):
    action = BUTTON_ACTIONS[direction]
    results = []
    for i in range(ACTION_REPEAT):
        results.append(f"{action} ")
        if direction == 'up':
            d = bytes.fromhex('FF 01 00 08 00 05 0E')
            serr.send(d)
            time.sleep(3)
            d = bytes.fromhex('FF 01 00 00 00 00 01')
            serr.send(d)
        if direction == 'down':
            d = bytes.fromhex('FF 01 00 10 00 05 16')
            serr.send(d)
            time.sleep(3)
            d = bytes.fromhex('FF 01 00 00 00 00 01')
            serr.send(d)
        if direction == 'left':
            d = bytes.fromhex('FF 01 00 04 05 00 0A')
            serr.send(d)
            time.sleep(3)
            d = bytes.fromhex('FF 01 00 00 00 00 01')
            serr.send(d)
        if direction == 'right':
            d = bytes.fromhex('FF 01 00 02 05 00 08')
            serr.send(d)
            time.sleep(3)
            d = bytes.fromhex('FF 01 00 00 00 00 01')
            serr.send(d)
        if direction == 'stop':
            d = bytes.fromhex('FF 01 00 00 00 00 01')
            serr.send(d)

        print(f"{action} ")

    return jsonify(results=results)


if __name__ == '__main__':
    app.run(debug=False)